package com.ithe.shopweb.controller;

import cn.hutool.core.io.FileUtil;
import com.ithe.shopweb.common.Constants;
import com.ithe.shopweb.common.Result;
import com.ithe.shopweb.pojo.Offer;
import com.ithe.shopweb.pojo.resp.OfferResp;
import com.ithe.shopweb.serve.PersonServe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 功能：
 * 日期： 2024/5/22 16:35
 */
@RestController
@RequestMapping("/person")
public class PersonController implements Constants {

    @Autowired
    private PersonServe personServe;

    @Value("${file.temp}")
    private String tempPath;

    @Value("${file.path}")
    private String filePath;

    @PostMapping("/offerList")
    public Result personTable(@RequestBody Offer offer) {
        String offerUser = offer.getOfferUser();
        String offerID = offer.getOfferID();
        Integer pageNum = offer.getPageNum();
        Integer pageSize = offer.getPageSize();
        List<OfferResp> offerResp = personServe.personTable(offerUser, offerID, (pageNum-1)*pageSize, pageSize);
        Integer totalNum = personServe.offerAll(offerUser, offerID).size();

        Map<String, Object> offerTable = new HashMap<>();
        offerTable.put("total", totalNum);
        offerTable.put("data", offerResp);

        if(offerResp == null)
            return Result.error(CODE_400, "该用户无售卖商品");
        else
            return Result.success(offerTable);
    }

    @PostMapping("/cartList")
    public Result cartTable(@RequestBody Offer offer) {
        String cartUser = offer.getCartUser();
        String offerID = offer.getOfferID();
        Integer pageNum = offer.getPageNum();
        Integer pageSize = offer.getPageSize();
        List<OfferResp> offerResp = personServe.cartTable(cartUser, offerID, (pageNum-1)*pageSize, pageSize);
        for(OfferResp offerCell : offerResp) {
            String offerUser = personServe.nameTransform(offerCell.getOfferUser());
            offerCell.setOfferUser(offerUser);
        }
        Integer totalNum = personServe.cartAll(cartUser, offerID).size();

        Map<String, Object> cartTable = new HashMap<>();
        cartTable.put("total", totalNum);
        cartTable.put("data", offerResp);

        if(cartTable.get("data") == null)
            return Result.error(CODE_400, "购物车暂无商品");
        else
            return Result.success(cartTable);
    }

    @PostMapping("/recordList")
    public Result recordList(@RequestBody Offer offer) {
        String cartUser = offer.getCartUser();
        String offerID = offer.getOfferID();
        Integer pageNum = offer.getPageNum();
        Integer pageSize = offer.getPageSize();
        List<OfferResp> offerResp = personServe.recordTable(cartUser, offerID, (pageNum-1)*pageSize, pageSize);
        Integer totalNum = personServe.recordAll(cartUser, offerID).size();

        Map<String, Object> recordTable = new HashMap<>();
        recordTable.put("total", totalNum);
        recordTable.put("data", offerResp);

        if(recordTable.get("data") == null)
            return Result.error(CODE_400, "购物车暂无商品");
        else
            return Result.success(recordTable);
    }

    @PostMapping("/offerDelete")
    public Result offerDelete(@RequestBody Offer offer) {
        String offerID = offer.getOfferID();
        Integer number = personServe.offerDelete(offerID);
        if(number == 1) {
            return Result.success();
        } else {
            return Result.error(CODE_500, "删除商品失败");
        }
    }

    @PostMapping("/cartDelete")
    public Result cartDelete(@RequestBody Offer offer) {
        String offerID = offer.getOfferID();
        Integer number = personServe.cartDelete(offerID);
        if(number == 1) {
            return Result.success();
        } else {
            return Result.error(CODE_500, "删除商品失败");
        }
    }

    @PostMapping("/cartBuy")
    public Result cartBuy(@RequestBody Offer offer) {
        String offerID = offer.getOfferID();
        String offerUser = offer.getOfferUser();
        String offerImage = offer.getOfferImage();
        String offerName = offer.getOfferName();
        String offerStyle = offer.getOfferStyle();
        String offerState = offer.getOfferState();
        String offerLocal = offer.getOfferLocal();
        String offerDegree = offer.getOfferDegree();
        Double finalPrice = offer.getFinalPrice();
        String userLocal = offer.getUserLocal();
        String cartUser = offer.getCartUser();
        Integer number = personServe.cartBuy(offerID, offerImage, offerName, offerStyle, offerState, offerLocal, offerDegree, finalPrice, userLocal, offerUser, cartUser);
        if(number == 1)
            return Result.success();
        else
            return Result.error(CODE_500, "服务器异常");
    }

    @PostMapping("/offerAdd")
    public Result offerAdd(@RequestBody Offer offer) {
        String offerUser = offer.getOfferUser();
        String offerImage = copyImage(offer.getOfferImage());
        String offerName = offer.getOfferName();
        String offerStyle = offer.getOfferStyle();
        Double offerPrice = offer.getOfferPrice();
        String offerLocal = offer.getOfferLocal();
        String offerDiscount = offer.getOfferDiscount();
        String offerDegree = offer.getOfferDegree();
        Double finalPrice = offer.getFinalPrice();
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyMMddss");
        String offerID = offerUser + now.format(formatter);
        Integer number = personServe.offerAdd(offerID, offerImage, offerName, offerStyle, offerPrice, offerLocal, offerDiscount, offerDegree, finalPrice, offerUser);
        if(number == 1)
            return Result.success();
        else
            return Result.error(CODE_500, "服务器异常");
    }

    @PostMapping("/uploadImage")
    public Result uploadImage(MultipartFile file) {
        try {
            // 获取文件的原始名称
            String originalFilename = file.getOriginalFilename();

            // 获取文件的名称和后缀名
            String mainName = FileUtil.mainName(originalFilename);
            String extName = FileUtil.extName(originalFilename);

            // 设置文件存储的路径，并将文件名添加到路径
            String filesPath = tempPath;
            String fileRealPath = Paths.get(filesPath, originalFilename).toString();

            File saveFile = new File(fileRealPath);
            // 如果文件已存在，则在文件名中添加一个时间戳
            if (saveFile.exists()) {
                String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
                String newFilename = mainName + "_" + timestamp + "." + extName;
                fileRealPath = Paths.get(filesPath, newFilename).toString();
                saveFile = new File(fileRealPath);
            }

            // 如果父级目录不存在则创建
            if (!saveFile.getParentFile().exists()) {
                saveFile.getParentFile().mkdirs();
            }

            // 保存文件
            file.transferTo(saveFile);
            return Result.success(saveFile.getName());
        } catch (Exception e) {
            return Result.error(Result.CODE_SYS_ERROR, "图片上传错误");
        }
    }

    @PostMapping("/photoRemove")
    public Result photoRemove(@RequestBody Map<String, String> param) {
        String fileName = param.get("fileName");

        // 设置文件存储的路径
        String filePath = tempPath;
        String imagePath = filePath + "\\" + fileName;
        try {
            Files.deleteIfExists(Paths.get(imagePath));
        } catch (IOException e) {
            return Result.error(Result.CODE_SYS_ERROR, "删除图片失败");
        }

        return Result.success("删除图片成功");
    }

    public String copyImage(String imageName) {
        File srcFile = new File(tempPath + imageName);
        File destFile = new File(filePath + imageName);

        try {
            if (destFile.exists()) {
                // 如果目标文件已经存在，添加时间戳做为新的文件名。
                String newName = addTimestamp(imageName);
                destFile = new File(filePath + newName);
            }
            Files.copy(srcFile.toPath(), destFile.toPath());
            return "http://118.178.132.147:8088/images/" + destFile.getName();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "图片Copy失败";
    }

    private String addTimestamp(String imageName) {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
        int dotIndex = imageName.lastIndexOf('.');
        if (dotIndex > 0) {
            return imageName.substring(0, dotIndex) + '_' + timestamp + imageName.substring(dotIndex);
        } else {
            return imageName + '_' + timestamp;
        }
    }

}
